package cn.jtfadmin.base.filesystem.controller;


import cn.afterturn.easypoi.excel.ExcelXorHtmlUtil;
import cn.afterturn.easypoi.excel.entity.ExcelToHtmlParams;
import cn.jtfadmin.base.filesystem.config.FileSystem;
import cn.jtfadmin.base.lang.common.utils.FileTypeUtils;
import cn.jtfadmin.base.lang.common.utils.RequestUtils;
import cn.jtfadmin.base.lang.enums.FileType;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.SystemUtils;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;

/**
 * 文件-图片预览controller
 *
 * @author jtf
 * @since 0.0.1
 */
@RestController
public class FilePrewController {

    @Autowired
    private FileSystem fileSystem;

    // 处理图片预览
    private void handleImgPrew(HttpServletRequest request, HttpServletResponse response, String pathName) {
        response.setContentType(MediaType.IMAGE_PNG_VALUE);
        long fileLength = fileSystem.getFileLength(pathName);
        if (fileLength < 0) {
            // 文件不存在
            return;
        }
        if (fileLength < 1024 * 200) {
            // 小于200K
            try (InputStream in = fileSystem.getFileInputStream(pathName)) {
                ServletOutputStream outputStream = response.getOutputStream();
                StreamUtils.copy(in, outputStream);
            } catch (Exception ex) {
                //
            }
            return;
        }
        // 写入临时文件
        File temFile = new File(SystemUtils.getJavaIoTmpDir(), pathName);
        if (!temFile.getParentFile().exists()) {
            temFile.getParentFile().mkdirs();
        }
        if (!temFile.exists()) {
            try (InputStream in = fileSystem.getFileInputStream(pathName)) {
                Thumbnails.of(in)
                        .outputQuality(1f)
                        .width(96)
                        .height(96)
                        .toFile(temFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try (InputStream in = new FileInputStream(temFile)) {
            ServletOutputStream outputStream = response.getOutputStream();
            StreamUtils.copy(in, outputStream);
        } catch (Exception ex) {
            //
        }
    }

    /**
     * 图片预览， 后面的** 代表图片路径
     *
     * @return
     */
    @GetMapping(value = "/file/prew/**", produces = MediaType.IMAGE_PNG_VALUE)
    public void getUploadTypes() throws IOException {
        String preStr = "/file/prew";
        HttpServletRequest request = RequestUtils.getRequest();
        HttpServletResponse response = RequestUtils.getResponse();
        String requestURI = request.getRequestURI();
        String pathName = requestURI.substring(requestURI.indexOf(preStr) + preStr.length());
        if(pathName.equals("/") || pathName.equals("")){
            pathName = ObjectUtils.defaultIfNull(request.getParameter("url"), "");
        }
        pathName = URLDecoder.decode(pathName, "utf-8");
        String typeName = FileTypeUtils.getType(pathName);
        FileType fileType = FileTypeUtils.getFileType(typeName);
        if (fileType == null) {
            return;
        }
        if (fileType.equals(FileType.IMAGE)) {
            handleImgPrew(request, response, pathName);
        }else if(fileType.equals(FileType.TEXT)){
            response.setContentType(MediaType.TEXT_HTML_VALUE);
            try (InputStream in = fileSystem.getFileInputStream(pathName)) {
                ServletOutputStream outputStream = response.getOutputStream();
                StreamUtils.copy(in, outputStream);
            }
        }else if(fileType.equals(FileType.OFFICE_EXCEL)){
            response.setContentType(MediaType.TEXT_HTML_VALUE);
            try (InputStream in = fileSystem.getFileInputStream(pathName)) {
                ExcelToHtmlParams excelToHtmlParams = new ExcelToHtmlParams(
                        WorkbookFactory.create(in), true, "notNull"
                );
                String s = ExcelXorHtmlUtil.excelToHtml(excelToHtmlParams);
                response.getWriter().write(s);
            }

        }
        // TODO 其他格式
    }


//
//    /**
//     * word文件预览
//     *
//     * @param url url
//     * @return
//     */
//    @ResponseBody
//    @RequestMapping(value = "/file/word/preview", method = {RequestMethod.GET})
//    public ResultDTO<String> previewWord(@RequestParam @NotBlank String url) throws IOException, TransformerException, ParserConfigurationException, Docx4JException {
//
//        RestTemplate restTemplate = getRestTemplate();
//        InputStream inputStream = restTemplate.execute(url, HttpMethod.GET, null, (response) -> {
//            return new ByteArrayInputStream(StreamUtils.copyToByteArray(response.getBody()));
//        });
//        WordprocessingMLPackage wordMLPackage = Docx4J.load(inputStream);
//
//        HTMLSettings htmlSettings = Docx4J.createHTMLSettings();
//
//        htmlSettings.setWmlPackage(wordMLPackage);
//
//
//
//        ByteArrayOutputStream os = new ByteArrayOutputStream();
//
//        Docx4jProperties.setProperty("docx4j.Convert.Out.HTML.OutputMethodXML", true);
//
//        return ResultDTO.successData(os.toString("utf-8"));
//    }

//    /**
//     * excel文件预览
//     *
//     * @param url url
//     * @return
//     */
//    @ResponseBody
//    @RequestMapping(value = "/file/excel/preview", method = {RequestMethod.GET})
//    public ResultDTO<String> previewExcel(@RequestParam @NotBlank String url) throws Exception {
//        RestTemplate restTemplate = getRestTemplate();
//        InputStream inputStream = restTemplate.execute(url, HttpMethod.GET, null, (response) -> {
//            return new ByteArrayInputStream(StreamUtils.copyToByteArray(response.getBody()));
//        });
//        byte[] bytes = new ExcelTransformer().transforToHtml(url.substring(url.lastIndexOf(".")), inputStream);
//        return ResultDTO.successData(new String(bytes, "utf-8"));
//    }


//    private RestTemplate getRestTemplate() {
//        if (restTemplate == null) {
//            try {
//                restTemplate = ApplicationHolder.getApplicationContext().getBean(RestTemplate.class);
//            } catch (Exception ex) {
//                restTemplate = new RestTemplate();
//            }
//
//        }
//        return restTemplate;
//    }

    //
//    /**
//     * word文件预览
//     *
//     * @param url url
//     * @return
//     */
//    @ResponseBody
//    @RequestMapping(value = "/file/word/preview", method = {RequestMethod.GET})
//    public ResultDTO<String> previewWord(@RequestParam @NotBlank String url) throws IOException, TransformerException, ParserConfigurationException, Docx4JException {
//
//        RestTemplate restTemplate = getRestTemplate();
//        InputStream inputStream = restTemplate.execute(url, HttpMethod.GET, null, (response) -> {
//            return new ByteArrayInputStream(StreamUtils.copyToByteArray(response.getBody()));
//        });
//        WordprocessingMLPackage wordMLPackage = Docx4J.load(inputStream);
//
//        HTMLSettings htmlSettings = Docx4J.createHTMLSettings();
//
//        htmlSettings.setWmlPackage(wordMLPackage);
//
//
//
//        ByteArrayOutputStream os = new ByteArrayOutputStream();
//
//        Docx4jProperties.setProperty("docx4j.Convert.Out.HTML.OutputMethodXML", true);
//
//        return ResultDTO.successData(os.toString("utf-8"));
//    }

//    /**
//     * excel文件预览
//     *
//     * @param url url
//     * @return
//     */
//    @ResponseBody
//    @RequestMapping(value = "/file/excel/preview", method = {RequestMethod.GET})
//    public ResultDTO<String> previewExcel(@RequestParam @NotBlank String url) throws Exception {
//        RestTemplate restTemplate = getRestTemplate();
//        InputStream inputStream = restTemplate.execute(url, HttpMethod.GET, null, (response) -> {
//            return new ByteArrayInputStream(StreamUtils.copyToByteArray(response.getBody()));
//        });
//        byte[] bytes = new ExcelTransformer().transforToHtml(url.substring(url.lastIndexOf(".")), inputStream);
//        return ResultDTO.successData(new String(bytes, "utf-8"));
//    }


//    private RestTemplate getRestTemplate() {
//        if (restTemplate == null) {
//            try {
//                restTemplate = ApplicationHolder.getApplicationContext().getBean(RestTemplate.class);
//            } catch (Exception ex) {
//                restTemplate = new RestTemplate();
//            }
//
//        }
//        return restTemplate;
//    }
}
